package com.cjj2016.cjj.mylyricviewdemo.widget;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by CJJ on 2017/2/12.
 */

public class MyFloatView {
    private static final int HIDE_FLOATVIEW = 1;

    private Context mContext;

    private WindowManager mWindowManager;

    private WindowManager.LayoutParams mLayoutParams;

    private View floatView;


    //手指按下与移动的x，y
    float downX,downY,endX,endY;
    //手指按下与抬起的时间
    private long downTimeMills,upTimeMills;

    //最后的x，y
    float lastX,lastY;

    private View menuView;


    //屏幕宽高信息
    private DisplayMetrics mDisplayMetrics;


    private boolean upFlag=true;//手指是否离开屏幕

    //当前显示的view
    private View contentView;
    //当前显示view的宽高
    private float contentViewWidth,contentViewHeight;

    private boolean showMenuViewFlag=false;//显示按钮菜单标识

    private boolean isShowing = false;//是否已显示floatview

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case HIDE_FLOATVIEW:
                    if( upFlag && !showMenuViewFlag ){
                        updateViewAlpha(0.5f);
                    }

                    break;
            }
        }
    };


   public MyFloatView(Context context,View fview,View mView){
       mContext = context;

       floatView = fview;
       menuView = mView;

       mWindowManager = (WindowManager)context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

       mLayoutParams = new WindowManager.LayoutParams();
       mLayoutParams.flags = mLayoutParams.flags
//                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
               | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
               | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
       mLayoutParams.dimAmount = 0.2f;
       mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
       mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
       mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
       mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
       mLayoutParams.format = PixelFormat.RGBA_8888;
       mLayoutParams.alpha = 1.0f;//整个窗口的透明度


       floatView.setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
               switch (event.getAction()){
                   case MotionEvent.ACTION_DOWN:
                       down(event);
                       break;
                   case MotionEvent.ACTION_MOVE:
                       move(event);
                       break;
                   case MotionEvent.ACTION_UP:
                       up(event);
                       break;

               }
               return false;
           }
       });

       menuView.setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
               switch (event.getAction()){
                   case MotionEvent.ACTION_OUTSIDE:
                       //轮廓外的touch事件
                       showFloatView();
                       break;
               }

               return false;
           }
       });



       //首先加载floatview
       createContentView(floatView);



       //屏幕的宽高
       mDisplayMetrics = new DisplayMetrics();
       mWindowManager.getDefaultDisplay().getMetrics(mDisplayMetrics);
   }


    private void down(MotionEvent event){
        downX= event.getRawX();
        downY =event.getRawY();
        downTimeMills =  System.currentTimeMillis();

        upFlag = false;
        mHandler.removeMessages(HIDE_FLOATVIEW);
        updateViewAlpha(1.0f);
    }


    private void move(MotionEvent event){
        endX = event.getRawX() - contentViewWidth/2;
        endY = event.getRawY() - getStatusBarHeight()- contentViewHeight/2;
        updateViewLocation(endX,endY);

    }

    private void up(MotionEvent event){
        upFlag = true;

        //判断最后的x点是否大于整个屏幕的宽度的一半
        // 自动贴到屏幕的最右侧或者最最左侧
        if(endX >= mDisplayMetrics.widthPixels/2 - contentViewWidth/2 ){
            doAlignAnimator(endX, mDisplayMetrics.widthPixels - contentViewHeight/2 );

            lastX =  mDisplayMetrics.widthPixels - contentViewHeight/2;
        }else {
            doAlignAnimator(endX,0);

            lastX = 0;
        }

        upTimeMills = System.currentTimeMillis();
        if( upTimeMills - downTimeMills > 200){
            //长按

        }else {
            //点击
            ShowMenuView();

        }


    }

    //显示menuView
    private void ShowMenuView() {

        if(showMenuViewFlag)
        {
            return;
        }

        //移除之前的floatview
        mWindowManager.removeView(contentView);

        createContentView(menuView);
        mLayoutParams.flags = mLayoutParams.flags
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; //接受轮廓外的touch事件
        mLayoutParams.x = (int) (mDisplayMetrics.widthPixels/2 -contentViewWidth/2);
        mLayoutParams.y = (int) (mDisplayMetrics.heightPixels/2 - contentViewHeight/2- getStatusBarHeight());
        mWindowManager.addView(contentView,mLayoutParams);
        showMenuViewFlag = true;

    }

    //显示floatview
    private void showFloatView() {
        if( !showMenuViewFlag)
        {
            return;
        }


        mWindowManager.removeView(contentView);

        createContentView(floatView);
        mLayoutParams.flags &= ~WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; //取消接受轮廓外的touch事件
        mLayoutParams.x = (int) lastX;
        mLayoutParams.y = (int) lastY;
        mWindowManager.addView(contentView,mLayoutParams);

        showMenuViewFlag =false;
        mHandler.sendEmptyMessageDelayed(HIDE_FLOATVIEW,3000);
    }


    private void createContentView(View view){
        contentView = view;
        // 主动计算视图View的宽高信息
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        contentViewWidth = view.getMeasuredWidth();
        contentViewHeight = view.getMeasuredWidth();
    }


    //自动贴到屏幕动画
    private void  doAlignAnimator(float startVal, final float endVal){
        ValueAnimator alignAnimator = ValueAnimator.ofFloat(startVal,endVal);
        alignAnimator.setDuration(500);
        alignAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                updateViewLocation(value,endY);
            }
        });
        alignAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                //发送改变floatview透明度消息
                mHandler.sendEmptyMessageDelayed(HIDE_FLOATVIEW,3000);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                mHandler.removeMessages(HIDE_FLOATVIEW);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        alignAnimator.start();

    }

    //更新floatview的位置
    private  void  updateViewLocation(float x,float y){
        if( !showMenuViewFlag && contentView.equals(floatView)){
            mLayoutParams.x = (int) x;
            mLayoutParams.y = (int) y;
            mWindowManager.updateViewLayout(contentView,mLayoutParams);

            lastY = y;
        }

    }

    //更新floatview透明度
    private  void  updateViewAlpha(float alphaVal){
        if( !showMenuViewFlag && contentView.equals(floatView) && isShowing ) {
            mLayoutParams.alpha = alphaVal;
            mWindowManager.updateViewLayout(contentView, mLayoutParams);
        }
    }




    /**
     * 获取状态栏高度
     * */
    public int getStatusBarHeight(){
        int statusBarHeight = 0;
        //获取status_bar_height资源的ID
        int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight = mContext.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    /**
     * 显示Myfloatview
     */
    public void show(){
        if(contentView != null && !isShowing){
            mWindowManager.addView(contentView,mLayoutParams);
            mHandler.sendEmptyMessageDelayed(HIDE_FLOATVIEW,3000);
            isShowing=true;
        }
    }

    /**
     * 隐藏Myfloatview
     */
    public void hide(){
        if(contentView != null && isShowing){
            mWindowManager.removeView(contentView);
            isShowing = false;
        }
    }

    //获取是显示了myfloatview的标识值
    public boolean getShowing(){
        return isShowing;
    }

}
